module.exports = function ($scope, $resource, $stateParams, saleChannelList, wdnamelist, info,
    createorder, getuserinfobymobile, createSubsidyOrder, date2str, $modal, toaster, Excel, $timeout) {

    init();
    //初始化页面参数
    function init() {
        $scope.orderInfoShow = false;	//显示购票界面控制器
        $scope.saleobj = {};
        $scope.product = {};
        $scope.obj = {};
        //查询景区列表,并且将结果转换成树结构
        saleChannelList.get({ 'channel_list_code': $stateParams.code }, function (res) {
            if (res.errcode !== 0) {
                alert(res.errmsg);
                return;
            }
            $scope.treeData = {};
            res.data.forEach(function (item) {
                item.show = true;
                if (!$scope.treeData.hasOwnProperty(item.place_code)) {
                    $scope.treeData[item.place_code] = {
                        'sale_name': item.place_name,
                        'nodes': [],
                        'show': true
                    };
                }
                $scope.treeData[item.place_code].nodes.push(item);
            });
        });
    }

    //树结构列表选择,显示订单信息
    $scope.getInfo = function (obj) {
        if (!obj.id) return;		//不包含id为展开项,无法查看详细
        $scope.orderInfoShow = true;
        $scope.saleobj = obj;
        $scope.order = {
            'sale_code': obj.sale_code,
            'pay_method': 'account',
            'num': 1,
            'unavible': true
        };

        $scope.userList = [];

        $scope.obj.is_platform_sale = obj.is_platform_sale;
		$scope.obj.authorized_type = obj.authorized_type;
		$scope.obj.id = obj.id;
		$scope.obj.name = obj.sale_name;
		$scope.obj.price_type = obj.price_type;
		$scope.obj.govsubsidy_price = obj.govsubsidy_price;
        $scope.obj.tour_date_type = obj.tour_date_type;
        //更新出游时间
        $scope.section_date = {
            'label': date2str(new Date()),
            'value': date2str(new Date()),
            'opened': false
        };
        info.get({ 'id': obj.id }, function (res) {
            if (res.errcode === 0) {
                $scope.obj.detail = res.data.detail;
                $scope.obj.bookingnotes = res.data.bookingnotes;
            } else {
                $scope.orderInfoShow = false;
                alert(res.errmsg);
            }
        });
    };

    $scope.complete = false;
    //确认购买
    $scope.buy = function () {
        if (!$scope.userList.length) {
            toaster.warning({ title: '', body: "请添加购票人" });
            return false;
        }
        let temp_num = 0;
        for (let index = 0; index < $scope.userList.length; index++) {
            const element = $scope.userList[index];
            if (element.check && !element.is_exit_order) {
                temp_num++ ;
            }
        }
        if (!temp_num) {
            toaster.warning({title: '', body: '请添加有效的游客信息'})
            return false;
        }
        if (!confirm("您目前购买的是【" + $scope.obj.name + '】产品，有效游客【' + temp_num + '】人，请确认是否正确？')) {
            return false;
        }
        //按钮设置为不可用,防止连续点击下多单
        $scope.btnstate = true;
        if($scope.section_date.label == null){

		}else if (typeof $scope.section_date.label === 'string') {
			$scope.order.tour_date = $scope.section_date.label;
		} else {
			$scope.order.tour_date = date2str($scope.section_date.label);
		}
        $scope.realCreateOrder(0);
    };
    
    $scope.realCreateOrder = function (index) {
        if(index >= $scope.userList.length){
            return false;
        }
        const element = $scope.userList[index];
        if (!element.check || element.is_exit_order) {
            $scope.realCreateOrder(++index);
            return false;
        }
        element.tour_date = $scope.order.tour_date;
        element.num = $scope.order.num;
        element.pay_method = $scope.order.pay_method;
        $resource('/api/ac/tc/ticketOrderService/createOrderSubsidy', {}, {}).save(element, function (res) {
            if (res.errcode === 0) {
                toaster.success({ title: element.name, body: '下单成功，请注意查收短信' });
                element.msg = '成功，订单编号：' + res.data;
                element.is_exit_order = true;
            } else {
                element.msg = '失败：' + res.errmsg;
                toaster.error({ title: element.name, body: res.errmsg });
            }
            $scope.btnstate = false;
            $scope.realCreateOrder(++index);
        });
    }

    function check(obj) {
        obj.checking = true;
        obj.check = false;
        obj.num = $scope.order.num;
        obj.msg = "校验中......";
        if (!obj.name) {
            obj.checking = false;
            obj.msg = '请填写姓名';
            return false;
        }
        if (!obj.cardno) {
            obj.checking = false;
            obj.msg = '请填写身份证';
            return false;
        } else if (!checkCardNo(obj.cardno)) {
            obj.checking = false;
            obj.msg = '身份证信息有误';
            return false;
        }
        if (!obj.mobile) {
            obj.checking = false;
            obj.msg = '请填写购电话';
            return false;
        }
        if ($scope.obj.tour_date_type == '1' && $scope.order.tour_date == '') {
            obj.checking = false;
            obj.msg = '请填写出游时间，该票种只能在填写的出游时间使用。';
            return false;
        }
        $resource('/api/ac/tc/ticketOrderService/checkOrderSubsidy', {}, {}).save(obj, function (res) {
            if (res.errcode === 0) {
                obj.check = true;
                obj.checking = false;
                obj.msg = res.data;
                return true;
            } else {
                obj.checking = false;
                obj.msg = '失败：' + res.errmsg;
                return false;
            }
        });
    }

    function check2(index) {
        if (index >= $scope.userList.length) {
            return false;
        }
        let obj = $scope.userList[index];
        obj.checking = true;
        let temp_msg = '';
        obj.msg = "校验中......";
        obj.check = false;
        obj.num = $scope.order.num;
        if (!obj.name) {
            obj.checking = false;
            obj.msg = temp_msg + '请填写姓名';
            check2(++index)
            return false;
        }
        if (!obj.cardno) {
            obj.checking = false;
            obj.msg = temp_msg + '请填写身份证';
            check2(++index)
            return false;
        } else if (!checkCardNo(obj.cardno)) {
            obj.checking = false;
            obj.msg = temp_msg + '身份证信息有误';
            check2(++index)
            return false;
        }
        if (!obj.mobile) {
            obj.checking = false;
            obj.msg = temp_msg + '请填写购电话';
            check2(++index)
            return false;
        }
        if ($scope.obj.tour_date_type == '1' && $scope.order.tour_date == '') {
            obj.checking = false;
            obj.msg = '请填写出游时间，该票种只能在填写的出游时间使用。';
            check2(++index)
            return false;
        }
        $resource('/api/ac/tc/ticketOrderService/checkOrderSubsidy', {}, {}).save(obj, function (res) {
            if (res.errcode === 0) {
                obj.check = true;
                obj.msg = res.data;
                obj.checking = false;
                check2(++index)
                return false;
            } else {
                obj.checking = false;
                obj.msg = '失败：' + res.errmsg;
                check2(++index)
                return false;
            }
        });
    }

    //选择出游时间
    $scope.open = function ($event, item) {
        $event.preventDefault();
        $event.stopPropagation();
        item.opened = true;
    }

    $scope.selectDate = function () {
        var modalInstance = $modal.open({
            template: require('../views/sellPriceSetting.html'),
            controller: 'sellPriceSetting',
            size: 'lg',
            resolve: {
                items: function () {
                    return {
                        saleobj: $scope.saleobj
                    };
                }
            }
        });
        modalInstance.result.then(function (result) {
            $scope.section_date.label = date2str(new Date(result.date));
            $scope.product = result;
        });
    }

    $scope.visible = function (item) {
        return !($scope.query && $scope.query.length > 0 && item.sale_name.indexOf($scope.query) == -1);
    };

    //票数量增加或减少
    $scope.numModify = function (num) {
        $scope.order.num += num;
        if ($scope.order.num < 0) {
            $scope.order.num = 0;
        } else if ($scope.order.num > 99) {
            $scope.order.num = 99;
        }
    }

    $scope.userList = [];
    //导入excel
    $scope.excel = function () {
        var modalInstance = $modal.open({
            template: require('../views/addUserBatch.html'),
            controller: 'addUserBatch',
            size: 'lg',
            resolve: {
            }
        });
        //关闭模态框刷新页面
        modalInstance.result.then(function (result) {
            if (result && result.length > 0) {
                let index = $scope.userList.length;
                for (let index = 0; index < result.length; index++) {
                    const element = result[index];
                    element.sale_code = $scope.saleobj.sale_code;
                    element.num = $scope.order.num;
                    $scope.userList.push((element))
                }
                check2(index)
            }
        });
    }

    $scope.change = function (index) {
        if (!check($scope.userList[index])) {
            $scope.userList[index].unavible = true;
        } else {
            $scope.userList[index].unavible = false;
        }
    }

    $scope.add = function () {
        if ($scope.section_date.label == null) {

        } else if (typeof $scope.section_date.label === 'string') {
            $scope.order.tour_date = $scope.section_date.label;
        } else {
            $scope.order.tour_date = date2str($scope.section_date.label);
        }
        $scope.order.sale_code = $scope.saleobj.sale_code;
        // $scope.order.pay_method = 'account';
        // $scope.order.date = {
        //     'label': date2str(new Date()),
        //     'value': date2str(new Date()),
        //     'opened': false
        // };
        // //-------------- 参数验证 -----------------------//
        // if (!check($scope.order)) {
        //     return false;
        // }
        $scope.userList.push(angular.copy($scope.order))
    }

    $scope.removeAll = function (index) {
        $scope.userList = [];
        $scope.complete = false;
    }

    $scope.remove = function (index) {
        $scope.userList.splice(index, 1)
        if ($scope.userList.length == 0) {
            $scope.complete = false;
        }
    }

    $scope.ExcelName = date2str(new Date());
    $scope.exportToExcel = function (tableId) {
        $timeout(function () {
            document.getElementById("dlink").href = Excel.tableToExcel(tableId, 'sheet1');
            //document.getElementById("dlink").download = "1122b.xls";//这里是关键所在,当点击之后,设置a标签的属性,这样就可以更改标签的标题了
            document.getElementById("dlink").click();
        }, 100); // trigger download
    }

    var checkCardNo = function (code) {

        var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " };
        var tip = "";
        var pass = true;

        if (!code || !/^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/i.test(code)) {
            tip = "身份证号格式错误";
            pass = false;
        }

        else if (!city[code.substr(0, 2)]) {
            tip = "身份证地址编码错误";
            pass = false;
        }
        else {
            //18位身份证需要验证最后一位校验位
            if (code.length == 18) {
                code = code.split('');
                //∑(ai×Wi)(mod 11)
                //加权因子
                var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
                //校验位
                var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
                var sum = 0;
                var ai = 0;
                var wi = 0;
                for (var i = 0; i < 17; i++) {
                    ai = code[i];
                    wi = factor[i];
                    sum += ai * wi;
                }
                var last = parity[sum % 11];
                if (parity[sum % 11] != code[17]) {
                    tip = "身份证校验位错误";
                    pass = false;
                }
            }
        }
        // if(!pass) {
        //     toaster.warning({title: code, body: tip})
        // }
        return pass;

    }
};